<template>
    <div class="app-container">

        <!-- 查询条件 -->
        <el-card>
            <el-form ref="noticeRef" :inline="true" :model="queryParams" label-width="68px">
                <el-form-item label="公告标题" prop="noticeTitle">
                    <el-input v-model="queryParams.noticeTitle" placeholder="请输入公告标题" clearable style="width: 240px" />
                </el-form-item>

                <el-form-item label="操作人员" prop="createBy">
                    <el-input v-model="queryParams.createBy" placeholder="请输入操作人员" clearable style="width: 240px" />
                </el-form-item>

                <el-form-item label="类型" prop="noticeType">
                    <el-select v-model="queryParams.noticeType" placeholder="公告类型" clearable>
                        <el-option v-for="dict in sys_notice_type" :key="dict.value" :label="dict.label"
                            :value="dict.value" />
                    </el-select>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                    <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 表格 结果展示 -->
        <el-card style="margin-top: 20px;">

            <template #header>
                <el-row :gutter="10">
                    <el-col :span="1.5">
                        <el-button v-hasPermi="['system:notice:add']" type="primary" plain icon="Plus"
                            @click="handleAdd">新增</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button v-hasPermi="['system:notice:edit']" type="success" plain icon="Edit"
                            :disabled="single" @click="handleUpdate()">修改</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button v-hasPermi="['system:notice:remove']" type="danger" plain icon="Delete"
                            :disabled="multiple" @click="handleDelete()">删除</el-button>
                    </el-col>
                    <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
                </el-row>
            </template>

            <el-table v-loading="loading" :data="pageData.rows" style="width: 100%"
                @selectionChange="handleSelectionChange">
                <el-table-column type="selection" align="center" width="55" />
                <el-table-column label="序号" align="center" prop="noticeId" />
                <el-table-column label="公告标题" align="center" prop="noticeTitle" :show-overflow-tooltip="true" />
                <el-table-column label="公告类型" align="center" prop="noticeType" width="100">
                    <template #default="scope">
                        <dict-tag :options="sys_notice_type" :value="scope.row.noticeType" />
                    </template>
                </el-table-column>
                <el-table-column label="状态" align="center" prop="status">
                    <template #default="scope">
                        <dict-tag :options="sys_notice_status" :value="scope.row.status" />
                    </template>
                </el-table-column>
                <el-table-column label="创建者" align="center" prop="createBy" :show-overflow-tooltip="true" />
                <el-table-column label="创建时间" align="center" prop="createTime" width="180">
                    <template #default="scope">
                        <span>{{parseTime(scope.row.createTime)}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
                    <template #default="scope">
                        <el-button v-hasPermi="['system:notice:edit']" circle type="primary" icon="Edit"
                            @click="handleUpdate(scope.row)" />
                        <el-button v-hasPermi="['system:notice:remove']" circle type="danger" icon="Delete"
                            @click="handleDelete(scope.row)" />
                    </template>
                </el-table-column>
            </el-table>

            <pagination v-show="pageData.total > 0" v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize" :total="pageData.total" @pagination="getList" />
        </el-card>

        <!-- 新增修改对话框  -->
        <el-dialog v-model="open" :title="title" width="800" :close-on-click-modal="false">
            <el-form ref="editRef" :model="form" label-width="80px">
                <el-form-item label="公告标题" prop="noticeTitle">
                    <el-input v-model="form.noticeTitle" placeholder="请输入公告标题" />
                </el-form-item>

                <el-form-item label="公告类型" prop="noticeType"
                    :rules="[ { required: true, message: '该值不能为空', trigger: 'blur'}]">
                    <el-select v-model="form.noticeType" placeholder="请选择" clearable>
                        <el-option v-for="dict in sys_notice_type" :key="dict.value" :label="dict.label"
                            :value="dict.value" />
                    </el-select>
                </el-form-item>

                <el-form-item label="公告状态" prop="status"
                    :rules="[ { required: true, message: '该值不能为空', trigger: 'blur'}]">
                    <el-radio-group v-model="form.status">
                        <el-radio v-for="dict in sys_notice_status" :key="dict.value"
                            :label="dict.value">{{ dict.label }}</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="公告内容" prop="noticeContent">
                    <!-- <el-input v-model="form.noticeContent" type="textarea" placeholder="请输入公告内容" /> -->
                    <editor v-model="form.noticeContent" placeholder="请输入公告内容" :min-height="192" />
                </el-form-item>

            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>

    </div>
</template>

<script setup name="Notice" lang="ts">
    import { ref, reactive, toRefs, getCurrentInstance, ComponentInternalInstance } from 'vue';
    import { SysNoticeQueryReq, FormReq, SysNoticeResp } from '@/types/notice';
    import { listNotice, getNotice, updateNotice, addNotice, delNotice } from '@/api/system/notice';
    import { parseTime } from '@/utils/ruoyi';
    import type { FormInstance } from 'element-plus';

    // 获取当前vue3的页面this对象转换为proxy代理，查询 sys_dict_data表中的值
    const { proxy } = getCurrentInstance() as ComponentInternalInstance;
    const { sys_notice_type, sys_notice_status } = proxy!.useDict('sys_notice_type', 'sys_notice_status');

    // 访问时加载动画
    const loading = ref<boolean>(false);

    // 默认不启用编辑按钮
    const single = ref<boolean>(true);
    //默认不启用删除按钮
    const multiple = ref<boolean>(true);
    const showSearch = ref<boolean>(true);
    // 表格选中的值
    const mutilSelection = ref<SysNoticeResp[]>([]);
    // 表格选中的主键的值
    const ids = ref<number[]>([]);

    // 对话框配置
    const open = ref(false);
    const title = ref('');

    // 表单验证对象
    const editRef = ref<FormInstance>();

    // 分页数据
    const pageData = reactive<{
        total : number;
        rows : SysNoticeResp[]
    }>({
        total: 0,
        rows: []
    })

    // 响应式代理模型
    const data = reactive<{
        form : FormReq;
        queryParams : SysNoticeQueryReq;
    }>({
        form: {
            noticeId: undefined,
            noticeTitle: '',
            noticeType: '',
            noticeContent: '',
            status: ''
        },
        queryParams: {
            noticeTitle: '',
            createBy: '',
            noticeType: '',
            pageNum: 1,
            pageSize: 10
        }
    })


    // 代理模型转为相应模型
    const { queryParams, form } = toRefs(data)

    // 重置查询条件
    function resetQuery() {
        proxy?.resetForm('noticeRef');
        //查询
        handleQuery();
    }

    // 查询
    function handleQuery() {
        queryParams.value.pageNum = 1;
        getList();
    }

    // 分页查询
    function getList() {
        loading.value = true;

        // 添加日期值
        listNotice(queryParams.value).then((resp : any) => {
            pageData.total = resp.data.total;
            pageData.rows = resp.data.list;
            loading.value = false;
        });
    }

    // 多选框选中数据
    function handleSelectionChange(selection : SysNoticeResp[]) {
        mutilSelection.value = selection;
        ids.value = selection.map(row => row.noticeId);
        // 修改按钮禁用值判断
        single.value = selection.length !== 1;
        // 删除按钮禁用值判断
        multiple.value = selection.length === 0;
    }

    // 新增
    function handleAdd() {
        reset();
        title.value = '通知公告--新增';
        open.value = true;
    }

    // 修改
    function handleUpdate(row ?: null | SysNoticeResp) {
        let primaryKey : number;
        if (row) {
            primaryKey = row.noticeId;
        } else {
            primaryKey = ids.value[0];
        }

        // 重置表单
        reset();

        // 根据id查询
        getNotice(primaryKey).then((resp : any) => {
            form.value = resp.data;
            title.value = '通知公告--修改';
            open.value = true;
        });
    }

    // 删除 或 禁用
    function handleDelete(row ?: SysNoticeResp) {
        let primaryKeys : any;
        if (row) {
            primaryKeys = row.noticeId;
        } else {
            primaryKeys = ids.value;
        }

        proxy?.$modal
            .confirm('是否确认删除参数编号为"' + primaryKeys + '"的数据项？')
            .then(function () {
                return delNotice(primaryKeys);
            })
            .then(() => {
                getList();
                proxy!.$modal.msgSuccess('删除成功');
            })
            .catch((e : any) => {
                console.log(e);
            });
    }

    // 去掉富文本框 p 标签
    function delHtmlTag(str : any) {
        return str.replace(/<[^>]+>/g, "");
    }

    // 新增或修改 提交按钮
    async function submitForm() {
        if (!editRef.value) {
            return;
        }

        form.value.noticeContent = delHtmlTag(form.value.noticeContent);

        await editRef.value.validate((valid : boolean, fields : any) => {
            if (valid) {
                // 调用修改请求
                if (form.value.noticeId) {
                    updateNotice(form.value).then(() => {
                        proxy?.$modal.msgSuccess('修改成功');
                        open.value = false;
                        getList();
                    });
                } else {
                    //调用新增请求
                    addNotice(form.value).then(() => {
                        proxy?.$modal.msgSuccess('新增成功');
                        open.value = false;
                        getList();
                    });
                }

            } else {
                console.log('error submit!', fields);
            }
        });
    }

    // 新增或修改 对话框取消按钮
    function cancel() {
        open.value = false;
    }

    /** 表单重置 */
    function reset() {
        form.value = {
            noticeId: undefined,
            noticeTitle: '',
            noticeType: '',
            noticeContent: '',
            status: '0'
        };
        // 重置表单样式
        form.value.noticeContent = '<p></p>'
        proxy?.resetForm('editRef');
    }

    // 初始化查询
    getList()
</script>
